﻿using IDLETD.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Animation;

namespace IDLETD.FSM
{
    public class FSMCore
    {
        public object Onwer;

        //当前状态 抽象类
        public StateBase CurState;

        //上一个状态
        public StateBase PervState;

        //当前状态执行时需要的数据 抽象类
        public object[] Curdata;

        //状态字典
        public Dictionary<StateEnum, StateBase> StateDic = new Dictionary<StateEnum, StateBase>();

        /// <summary>
        /// 注册状态
        /// </summary>
        /// <param name="key">状态枚举</param>
        /// <param name="value">状态实例</param>
        /// <returns></returns>
        public bool RegisterState(StateEnum key, StateBase value)
        {
            if (StateDic.ContainsKey(key)) return false;
            StateDic.Add(key, value);
            return true;
        }

        /// <summary>
        /// 状态切换
        /// </summary>
        /// <param name="state">新状态</param>
        /// <param name="data">新状态需要的数据</param>
        public bool ChangeState(StateEnum state, object[] data)
        {
            if (PervState != null && state == PervState.State) return false;
            StateBase newState;
            StateDic.TryGetValue(state, out newState);
            if (newState == null) return false;
            if (CurState != null)
            {
                if (CurState.State == state) return false;
                CurState.Leave();
            }
            PervState = CurState;
            CurState = newState;
            CurState.Enter(data);
            return true;
        }

        public void Excute()
        {
            CurState.Excute();
        }
    }
}
